MultiPrice AlertThis is an alert script using Pinescript version 4. This enables one to set 5 alerts (1 StopLoss, 4 Targets), on 3 different symbols, at using a single alert in the UI.
Every visible line will only appear on the symbols that are selected. After setting targets when making an alert, select this indicator as a condition. Change the name to whatever you want, usually the names of the set of tickers.
The Alert message is dyanmic showing which Symbol with each type of alert, at whatever price.
Ability to disable the targets + symbols.
Alerts work by Stop Loss crossing under price and Targets Cross Over. Enabling the "Short" Targets reverses this.
The line that is being displayed is actually the price of the asset being moved over x number of bars. I have not found a way to plot a traditional horizontal line, as the code for it uses a fixed price.
As it being a user input, it is a variable. Any help with this would be appreicated.
Alerts are set to once per bar.
Known bug that sometimes if the prices that you set are inside the current candle stick, then your alert will immeaditally fire, either change the timeframe or let it fire and wait fo
After a target is hit, I reccomend setting the alert to 0 and REMAKING the alert. You MUST REMAKE THE ALERT AFTER ANY CHANGES. This script WILL NOT CHANGE ALERTS AS YOU CHANGE SETTINGS.
TradingView Alerts are not this smart , at least I haven't found a way to do this yet.
"stop loss"に関するスクリプトを検索
Anti-Volume Stop Loss multi timeframe [LM]Hello Traders,
I would like to introduce you fork of popular indicator Anti-Volume Stop Loss created by Buff Dormeier and cracked here on tradingview by @Rafka so shout out to him. I have tried to crack it myself as well as I'm big fan of Dormeier's work but it's not easy so really big thanks to Rafka
I have refactored original script and have included multi timeframe setting.
As its shown below you can select higher timeframe to track lower one:
Enjoy!
Bitlinc MARSI Study AST w/ Take Profit & Stop loss - beta 0.1This script is beta 0.1 - will update as soon as the script is tradable
This script is based on AST on a 10 minute timeframe. You can change the asset and the timeframe for any asset you want to trade, but for it to work correct ALL settings have to be testes in the Strategy section of the TradingView. Each assets and timeframe require a different mixture of settings. This is NOT a one settings fits all trading for all assets on any timeframe. Below are the settings and explanation on how it works.
How it fires a buy / sell:
The script will plot an RSI with upper and lower bands in a separate indicator window. The idea behind this script is to fire a LONG when MA crosses OVER lower band and fire a SHORT when the MA crosses under the lower band. Each order that fires is an OCO (Order Cancels Order) for pyramiding.
Settings:
You have full control of these settings as mentioned above, you must configure every part of this script for each asset and timeframe you trade.
- Length of MA
- Length
- Upper bands of RSI
- Lower bands of RSI
- Take profit percentage
- Stop loss percentage
- Month to start and end the strategy (within 2020)
- Day to start and end the strategy (within 2020)
- Quantity type
- Slippage
- Pyramiding
***Remember that after the signal to enter or exit a trade is fired, the alert will trigger AFTER the close of the candle that caused the tigger to fire
ATR Stop Loss LONG/SHORT by melihgulerYou can monitor the stop loss level according to ATR in 2 ways (Long/Short).
RSI + EMA+ MTF Stop-LossThis is a simple RSI with multiple MTF (No security) to help with direction short and long-term.
The rsi for the current chart has a noise reduction, while the rest are based on ma's.
I have supplied an extra flexible mtf rsi ma for potential adjustable/long-term stop-loss or direction identification.
Enjoy
RSI Stop LossExperiment for using RSI as a stop loss value, shows where the price will be when the RSI increases or decreases by a specified amount.
poki buy and sell Take profit and stop lossThis indicator is based on modelius model of lazy bear weis model with ATR for the buy=B sell =S
in addition there is Take profit and stop loss in % both for short and for long
next stage is to know the resistance level and support based on bollinger marked in blue and red dots
Also included Parabolic Sar (blue and red dots rising up or down)
The color of bulish or bearish zone is based on the cross of Hull avreage and linear regression ( for each time set may need different setting for accuracy )
So how to use this scrupt to better profit
1. if you have B signal and its on lower support level then its good starting place for buy. look at the Parabolic Sar if its in agreement. The exit can be either by S =sell, Take profit that you decide on % or by end of Parabolic SAR upward
2. exact the oposite for short
Play with setting for the desired results or change modify this script for your purpose
Pivot Stop LossHere we intend to use pivot points for stop loss and take profit. This has the added benefit of helping you to visualize support and resistance levels.
Hull modelius take profit and stop lossThis model has Hull moving average, fibs in form of Bollinger ,SMA and Modelius model with ATR for buy and sell power based on weis volume. Inside alerts for buy and sell. take profit and stop loss for both longs and shorts
so have fun
SL + TP Dynamics - By M.LolasStop Loss e Take Profit dinâmicos para operações semiautomatizadas.
By M.Lolas
STOP-LOSS-RSI with Edge-Preserving Filter Strategy V2Modified RSI strategy with entry and exit points.
I have allowed for High and Low risk for anyone interested in using it (NO GUARANTEES. DO YOUR OWN RESEARCH).
I will later consider incorporating the standard RSI for exit points. I am sure returns will increase based on current test runs :)
Returns look good based on the strategy result.
15m ORB + FVG Strategy (ChadAnt)Core Logic
The indicator's logic revolves around three main phases:
1. Defining the 15-Minute Opening Range (ORB)
The script calculates the highest high (rangeHigh) and lowest low (rangeLow) that occurred during the first 15 minutes of the trading day.
This time window is defined by the sessionStr input, which defaults to 0930-0945 (exchange time).
The high and low of this range are plotted as small gray dots once the session ends (rangeSet = true).
2. Identifying a Fair Value Gap (FVG) Setup
After the 15-minute range is set, the indicator waits for a breakout of either the range high or range low.
A "Strict FVG breakout" requires two conditions on the first candle that closes beyond the range:
The candle before the breakout candle ( bars ago) must have been inside the range.
The breakout candle ( bar ago) must have closed outside the range.
A Fair Value Gap (FVG) must form on the most recent three candles (the current bar and the two previous bars).
Bullish FVG (Long Setup): The low of the current bar (low) is greater than the high of the bar two periods prior (high ). This FVG represents a price inefficiency that the trade expects to fill.
Bearish FVG (Short Setup): The high of the current bar (high) is less than the low of the bar two periods prior (low ).
If a valid FVG setup occurs, the indicator marks a pending setup and draws a colored box to highlight the FVG area (Green for Bullish FVG, Red for Bearish FVG).
3. Trade Entry and Management
If a pending setup is identified, the trade is structured as a re-entry trade into the FVG zone:
Entry Price: Set at the outer boundary of the FVG, which is the low of the current bar for a Long setup, or the high of the current bar for a Short setup.
Stop Loss (SL): Set at the opposite boundary of the FVG, which is the low for a Long setup, or the high for a Short setup.
The trade is triggered (tradeActive = true) once the price retraces to the pendingEntry level.
Risk/Reward (RR) Targets: Three Take Profit (TP) levels are calculated based on the distance between the Entry and Stop Loss:
$$\text{Risk} = | \text{Entry} - \text{SL} |$$
$$\text{TP}n = \text{Entry} \pm (\text{Risk} \times \text{RR}n)$$
where $n$ is 1, 2, or 3, corresponding to the input $\text{RR}1$, $\text{RR}2$, and $\text{RR}3$ values (defaults: 1.0, 1.5, and 2.0).
Trade Lines: Upon triggering, lines for the Entry, Stop Loss, and three Take Profit levels are drawn on the chart for a specified length (lineLength).
A crucial feature is the directional lock (highBroken / lowBroken):
If the price breaks a range level (e.g., simpleBrokeHigh) but without a valid FVG setup, the corresponding directional flag (e.g., highBroken) is set to true permanently for the day.
This prevents the indicator from looking for any subsequent trade setups in that direction for the rest of the day, suggesting that the initial move, without an FVG, exhausted the opportunity.
Open-source script
In true TradingView spirit, the creator of this script has made it open-source, so that traders can review and verify its functionality. Kudos to the author! While you can use it for free, remember that republishing the code is subject to our House Rules.
ChadAnt
Disclaimer
The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied
15m ORB + FVG (ChadAnt)Core Logic
The indicator's logic revolves around three main phases:
1. Defining the 15-Minute Opening Range (ORB)
The script calculates the highest high (rangeHigh) and lowest low (rangeLow) that occurred during the first 15 minutes of the trading day.
This time window is defined by the sessionStr input, which defaults to 0930-0945 (exchange time).
The high and low of this range are plotted as small gray dots once the session ends (rangeSet = true).
2. Identifying a Fair Value Gap (FVG) Setup
After the 15-minute range is set, the indicator waits for a breakout of either the range high or range low.
A "Strict FVG breakout" requires two conditions on the first candle that closes beyond the range:
The candle before the breakout candle ( bars ago) must have been inside the range.
The breakout candle ( bar ago) must have closed outside the range.
A Fair Value Gap (FVG) must form on the most recent three candles (the current bar and the two previous bars).
Bullish FVG (Long Setup): The low of the current bar (low) is greater than the high of the bar two periods prior (high ). This FVG represents a price inefficiency that the trade expects to fill.
Bearish FVG (Short Setup): The high of the current bar (high) is less than the low of the bar two periods prior (low ).
If a valid FVG setup occurs, the indicator marks a pending setup and draws a colored box to highlight the FVG area (Green for Bullish FVG, Red for Bearish FVG).
3. Trade Entry and Management
If a pending setup is identified, the trade is structured as a re-entry trade into the FVG zone:
Entry Price: Set at the outer boundary of the FVG, which is the low of the current bar for a Long setup, or the high of the current bar for a Short setup.
Stop Loss (SL): Set at the opposite boundary of the FVG, which is the low for a Long setup, or the high for a Short setup.
The trade is triggered (tradeActive = true) once the price retraces to the pendingEntry level.
Risk/Reward (RR) Targets: Three Take Profit (TP) levels are calculated based on the distance between the Entry and Stop Loss:
$$\text{Risk} = | \text{Entry} - \text{SL} |$$
$$\text{TP}n = \text{Entry} \pm (\text{Risk} \times \text{RR}n)$$
where $n$ is 1, 2, or 3, corresponding to the input $\text{RR}1$, $\text{RR}2$, and $\text{RR}3$ values (defaults: 1.0, 1.5, and 2.0).
Trade Lines: Upon triggering, lines for the Entry, Stop Loss, and three Take Profit levels are drawn on the chart for a specified length (lineLength).
A crucial feature is the directional lock (highBroken / lowBroken):
If the price breaks a range level (e.g., simpleBrokeHigh) but without a valid FVG setup, the corresponding directional flag (e.g., highBroken) is set to true permanently for the day.
This prevents the indicator from looking for any subsequent trade setups in that direction for the rest of the day, suggesting that the initial move, without an FVG, exhausted the opportunity.
Hash Momentum IndicatorHash Momentum Indicator
Overview
The Hash Momentum Indicator provides real-time momentum-based trading signals with visual entry/exit markers and automatic risk management levels. This is the indicator version of the popular Hash Momentum Strategy, designed for traders who want signal alerts without backtesting functionality.
Perfect for: Live trading, automation via alerts, multi-indicator setups, and clean chart visualization.
What Makes This Indicator Special
1. Pure Momentum-Based Signals
Captures price acceleration in real-time - not lagging moving average crossovers. Enters when momentum exceeds a dynamic ATR-based threshold, catching moves as they begin accelerating.
2. Automatic Risk Management Visualization
Every signal automatically displays:
Entry level (white dashed line)
Stop loss level (red line)
Take profit target (green line)
Partial TP levels (dotted green lines)
3. Smart Trade Management
Trade Cooldown: Prevents overtrading by enforcing waiting period between signals
EMA Trend Filter: Only trades with the trend (optional)
Session Filters: Trade only during Tokyo/London/New York sessions (optional)
Weekend Toggle: Avoid low-liquidity weekend periods (optional)
4. Clean Visual Design
🟢 Tiny green dot = Long entry signal
🔴 Tiny red dot = Short entry signal
🔵 Blue X = Long exit
🟠 Orange X = Short exit
No cluttered labels or dashboard - just clean signals
5. Professional Alerts Ready
Set up TradingView alerts for:
Long signals
Short signals
Long exits
Short exits
How It Works
Step 1: Calculate Momentum
Momentum = Current Price - Price
Normalized by standard deviation for consistency
Must exceed ATR × Threshold to trigger
Step 2: Confirm Acceleration
Momentum must be increasing (positive momentum change)
Price must be moving in signal direction
Step 3: Apply Filters
EMA Filter: Long only above EMA, short only below EMA (if enabled)
Session Filter: Check if in allowed trading session (if enabled)
Weekend Filter: Block signals on Sat/Sun (if enabled)
Cooldown: Ensure minimum bars passed since last signal
Step 4: Generate Signal
All conditions met = Entry signal fires
Lines automatically drawn for entry, stop, and targets
Step 5: Exit Detection
Opposite momentum detected = Exit signal
Stop loss or take profit hit = Exit signal
Lines removed from chart
⚙️ Settings Guide
Core Strategy
Momentum Length (Default: 13)
Number of bars for momentum calculation. Higher values = stronger signals but fewer trades.
Aggressive: 10
Balanced: 13
Conservative: 18-24
Momentum Threshold (Default: 2.25)
ATR multiplier for signal generation. Higher values = only trade the biggest momentum moves.
Aggressive: 2.0
Balanced: 2.25
Conservative: 2.5-3.0
Risk:Reward Ratio (Default: 2.5)
Your target profit as a multiple of your risk. With 2.2% stop and 2.5 R:R, your target is 5.5% profit.
Conservative: 3.0+ (need 25% win rate to profit)
Balanced: 2.5 (need 29% win rate to profit)
Aggressive: 2.0 (need 33% win rate to profit)
ATH대비 지정하락률에 도착 시 매수 - 장기홀딩 선물 전략(ATH Drawdown Re-Buy Long Only)본 스크립트는 과거 하락 데이터를 이용하여, 정해진 하락 %가 발생하는 경우 자기 자본의 정해진 %만큼을 진입하게 설계되어진 스트레티지입니다.
레버리지를 사용할 수 있으며 기본적으로 셋팅해둔 값이 내장되어있습니다.(자유롭게 바꿔서 쓰시면 됩니다.) 추가적으로 2번의 진입 외에도 다른 진입 기준, 진입 %를 설정하실 수 있으며 - ChatGPT에게 요청하면 수정해줄 것입니다.
실제 사용용도로는 KillSwitch 기능을 꺼주세요. 바 돋보기 기능을 켜주세요.
ATH Drawdown Re-Buy Long Only 전략 설명
1. 전략 개요
ATH Drawdown Re-Buy Long Only 전략은 자산의 역대 최고가(ATH, All-Time High)를 기준으로 한 하락폭(드로우다운)을 활용하여,
특정 구간마다 단계적으로 롱 포지션을 구축하는 자동 재매수(Long Only) 전략입니다.
본 전략은 다음과 같은 목적을 가지고 설계되었습니다.
급격한 조정 구간에서 체계적인 분할 매수 및 레버리지 활용
ATH를 기준으로 한 명확한 진입 규칙 제공
실시간으로
평단가
레버리지
청산가 추정
계좌 MDD
수익률
등을 시각적으로 제공하여 리스크와 포지션 상태를 직관적으로 확인할 수 있도록 지원
※ 본 전략은 교육·연구·백테스트 용도로 제공되며,
어떠한 형태의 투자 권유 또는 수익을 보장하지 않습니다.
2. 전략의 핵심 개념
2-1. ATH(역대 최고가) 기준 드로우다운
전략은 차트 상에서 항상 가장 높은 고가(High)를 ATH로 기록합니다.
새로운 고점이 형성될 때마다 ATH를 갱신하고, 해당 ATH를 기준으로 다음을 계산합니다.
현재 바의 저가(Low)가 ATH에서 몇 % 하락했는지
현재 바의 종가(Close)가 ATH에서 몇 % 하락했는지
그리고 사전에 설정한 두 개의 드로우다운 구간에서 매수를 수행합니다.
1차 진입 구간: ATH 대비 X% 하락 시
2차 진입 구간: ATH 대비 Y% 하락 시
각 구간은 ATH가 새로 갱신될 때마다 한 번씩만 작동하며,
새로운 ATH가 생성되면 다시 “1차 / 2차 진입 가능 상태”로 초기화됩니다.
2-2. 첫 포지션 100% / 300% 특수 규칙
이 전략의 중요한 특징은 **“첫 포지션 진입 시의 예외 규칙”**입니다.
전략이 현재 어떠한 포지션도 들고 있지 않은 상태에서
최초로 롱 포지션을 진입하는 시점(첫 포지션)에 대해:
기본적으로는 **자산의 100%**를 기준으로 포지션을 구축하지만,
만약 그 순간의 가격이 ATH 대비 설정값 이상(예: 약 –72.5% 이상 하락한 상황) 이라면
→ 자산의 300% 규모로 첫 포지션을 진입하도록 설계되어 있습니다.
이 규칙은 다음과 같이 동작합니다.
첫 진입이 1차 드로우다운 구간에서 발생하든,
첫 진입이 2차 드로우다운 구간에서 발생하든,
현재 하락폭이 설정된 기준 이상(예: –72.5% 이상) 이라면
→ “이 정도 하락이면 첫 진입부터 더 공격적으로 들어간다”는 의미로 300% 규모로 진입
그 이하의 하락폭이라면
→ 첫 진입은 100% 규모로 제한
즉, 전략은 다음 두 가지 모드로 동작합니다.
일반적인 상황의 첫 진입: 자산의 100%
심각한 드로우다운 구간에서의 첫 진입: 자산의 300%
이 특수 규칙은 깊은 하락에서는 공격적으로, 평소에는 상대적으로 보수적으로 진입하도록 설계된 것입니다.
3. 전략 동작 구조
3-1. 매수 조건
차트 상 High 기준으로 ATH를 추적합니다.
각 바마다 해당 ATH에서의 하락률을 계산합니다.
사용자가 설정한 두 개의 드로우다운 구간(예시):
1차 구간: 예를 들어 ATH – 50%
2차 구간: 예를 들어 ATH – 72.5%
각 구간에 대해 다음과 같은 조건을 확인합니다.
“이번 ATH 구간에서 아직 해당 구간 매수를 한 적이 없는 상태”이고,
현재 바의 저가(Low)가 해당 구간 가격 이하를 찍는 순간
→ 해당 바에서 매수 조건 충족으로 간주
실제 주문은:
해당 구간 가격에 맞춰 롱 포지션 진입(리밋/시장가 기반 시뮬레이션) 으로 처리됩니다.
3-2. ATH 갱신과 진입 기회 리셋
차트 상에서 새로운 고점(High)이 기존 ATH를 넘어서는 순간,
ATH가 갱신되고,
1차 / 2차 진입 여부를 나타내는 내부 플래그가 초기화됩니다.
이를 통해, 시장이 새로운 고점을 돌파해 나갈 때마다,
해당 구간에서 다시 한 번씩 1차·2차 드로우다운 진입 기회를 갖게 됩니다.
4. 포지션 사이징 및 레버리지
4-1. 계좌 자산(Equity) 기준 포지션 크기 결정
전략은 현재 계좌 자산을 다음과 같이 정의하여 사용합니다.
현재 자산 = 초기 자본 + 실현 손익 + 미실현 손익
각 진입 구간에서의 포지션 가치는 다음과 같이 결정됩니다.
1차 진입 구간:
“자산의 몇 %를 사용할지”를 설정값으로 입력
설정된 퍼센트를 계좌 자산에 곱한 뒤,
다시 전략 내 레버리지 배수(Leverage) 를 곱하여 실제 포지션 가치를 계산
2차 진입 구간:
동일한 방식으로, 독립된 퍼센트 설정값을 사용
즉, 포지션 가치는 다음과 같이 계산됩니다.
포지션 가치 = 현재 자산 × (해당 구간 설정 % / 100) × 레버리지 배수
그리고 이를 해당 구간의 진입 가격으로 나누어 실제 수량(토큰 단위) 를 산출합니다.
4-2. 첫 포지션의 예외 처리 (100% / 300%)
첫 포지션에 대해서는 위의 일반적인 퍼센트 설정 대신,
다음과 같은 고정 비율이 사용됩니다.
기본: 자산의 100% 규모로 첫 포지션 진입
단, 진입 시점의 ATH 대비 하락률이 설정값 이상(예: –72.5% 이상) 일 경우
→ 자산의 300% 규모로 첫 포지션 진입
이때 역시 다음 공식을 사용합니다.
포지션 가치 = 현재 자산 × (100% 또는 300%) × 레버리지
그리고 이를 가격으로 나누어 실제 진입 수량을 계산합니다.
이 규칙은:
첫 진입이 1차 구간이든 2차 구간이든 동일하게 적용되며,
“충분히 깊은 하락 구간에서는 첫 진입부터 더 크게,
평소에는 비교적 보수적으로” 라는 운용 철학을 반영합니다.
4-3. 실레버리지(Real Leverage)의 추적
전략은 각 바 단위로 다음을 추적합니다.
바가 시작할 때의 기존 포지션 크기
해당 바에서 새로 진입한 수량
이를 바탕으로, 진입이 발생한 시점에 다음을 계산합니다.
실제 레버리지 = (포지션 가치 / 현재 자산)
그리고 차트 상에 예를 들어:
Lev 2.53x 와 같은 형식의 레이블로 표시합니다.
이를 통해, 매수 시점마다 실제 계좌 레버리지가 어느 정도였는지를 직관적으로 확인할 수 있습니다.
5. 시각화 및 모니터링 요소
5-1. 차트 상 시각 요소
전략은 차트 위에 다음과 같은 정보를 직접 표시합니다.
ATH 라인
High 기준으로 계산된 역대 최고가를 주황색 선으로 표시
평단가(평균 진입가) 라인
현재 보유 포지션이 있을 때,
해당 포지션의 평균 진입가를 노란색 선으로 표시
추정 청산가(고정형 청산가) 라인
포지션 수량이 변화하는 시점을 감지하여,
당시의 평단가와 실제 레버리지를 이용해 근사적인 청산가를 계산
이를 빨간색 선으로 차트에 고정 표시
포지션이 없거나 레버리지가 1배 이하인 경우에는 청산가 라인을 제거
매수 마커 및 레이블
1차/2차 매수 조건이 충족될 때마다 해당 지점에 매수 마커를 표시
"Buy XX% @ 가격", "Lev XXx" 형태의 라벨로
진입 비율과 당시 레버리지를 함께 시각화
레이블의 위치는 설정에서 선택 가능:
바 아래 (Below Bar)
바 위 (Above Bar)
실제 가격 위치 (At Price)
5-2. 우측 상단 정보 테이블
차트 우측 상단에는 현재 계좌·포지션 상태를 요약한 정보 테이블이 표시됩니다.
대표적으로 다음 항목들이 포함됩니다.
Pos Qty (Token)
현재 보유 중인 포지션 수량(토큰 기준, 절대값 기준)
Pos Value (USDT)
현재 포지션의 시장 가치 (수량 × 현재 가격)
Leverage (Now)
현재 실레버리지 (포지션 가치 / 현재 자산)
DD from ATH (%)
현재 가격 기준, 최근 ATH에서의 하락률(%)
Avg Entry
현재 포지션의 평균 진입 가격
PnL (%)
현재 포지션 기준 미실현 손익률(%)
Max DD (Equity %)
전략 전체 기간 동안 기록된 계좌 기준 최대 손실(MDD, Max Drawdown)
Last Entry Price
가장 최근에 포지션을 추가로 진입한 직후의 평균 진입 가격
Last Entry Lev
위 “Last Entry Price” 시점에서의 실레버리지
Liq Price (Fixed)
위에서 설명한 고정형 추정 청산가
Return from Start (%)
전략 시작 시점(초기 자본) 대비 현재 계좌 자산의 총 수익률(%)
이 테이블을 통해 사용자는:
현재 계좌와 포지션의 상태
리스크 수준
누적 성과
를 직관적으로 파악할 수 있습니다.
6. 시간 필터 및 라벨 옵션
6-1. 전략 동작 기간 설정
전략은 옵션으로 특정 기간에만 전략을 동작시키는 시간 필터를 제공합니다.
“Use Date Range” 옵션을 활성화하면:
시작 시각과 종료 시각을 지정하여
해당 구간에 한해서만 매매가 발생하도록 제한
옵션을 비활성화하면:
전략은 전체 차트 구간에서 자유롭게 동작
6-2. 진입 라벨 위치 설정
사용자는 매수/레버리지 라벨의 위치를 선택할 수 있습니다.
바 아래 (Below Bar)
바 위 (Above Bar)
실제 가격 위치 (At Price)
이를 통해 개인 취향 및 차트 가독성에 맞추어
시각화 방식을 유연하게 조정할 수 있습니다.
7. 활용 대상 및 사용 예시
본 전략은 다음과 같은 목적에 적합합니다.
현물 또는 선물 롱 포지션 기준 장기·스윙 관점 추매 전략 백테스트
“고점 대비 하락률”을 기준으로 한 규칙 기반 운용 아이디어 검증
레버리지 사용 시
계좌 레버리지·청산가·MDD를 동시에 모니터링하고자 하는 경우
특정 자산에 대해
“새로운 고점이 형성될 때마다
일정한 규칙으로 깊은 조정 구간에서만 분할 진입하고자 할 때”
실거래에 그대로 적용하기보다는,
전략 아이디어 검증 및 리스크 프로파일 분석,
자신의 성향에 맞는 파라미터 탐색 용도로 사용하는 것을 권장합니다.
8. 한계 및 유의사항
백테스트 결과는 미래 성과를 보장하지 않습니다.
과거 데이터에 기반한 시뮬레이션일 뿐이며,
실제 시장에서는
유동성
슬리피지
수수료 체계
강제청산 규칙
등 다양한 변수가 존재합니다.
청산가는 단순화된 공식에 따른 추정치입니다.
거래소별 실제 청산 규칙, 유지 증거금, 수수료, 펀딩비 등은
본 전략의 계산과 다를 수 있으며,
청산가 추정 라인은 참고용 지표일 뿐입니다.
레버리지 및 진입 비율 설정에 따라 손실 폭이 매우 커질 수 있습니다.
특히 **“첫 포지션 300% 진입”**과 같이 매우 공격적인 설정은
시장 급락 시 계좌 손실과 청산 리스크를 크게 증가시킬 수 있으므로
신중한 검토가 필요합니다.
실거래 연동 시에는 별도의 리스크 관리가 필수입니다.
개별 손절 기준
포지션 상한선
전체 포트폴리오 내 비중 관리 등
본 전략 외부에서 추가적인 안전장치가 필요합니다.
9. 결론
ATH Drawdown Re-Buy Long Only 전략은 단순한 “저가 매수”를 넘어서,
ATH 기준으로 드로우다운을 구조적으로 활용하고,
첫 포지션에 대한 **특수 규칙(100% / 300%)**을 적용하며,
레버리지·청산가·MDD·수익률을 통합적으로 시각화함으로써,
하락 구간에서의 규칙 기반 롱 포지션 구축과
리스크 모니터링을 동시에 지원하는 전략입니다.
사용자는 본 전략을 통해:
자신의 시장 관점과 리스크 허용 범위에 맞는
드로우다운 구간
진입 비율
레버리지 설정
다양한 시나리오에 대한 백테스트와 분석
을 수행할 수 있습니다.
다시 한 번 강조하지만,
본 전략은 연구·학습·백테스트를 위한 도구이며,
실제 투자 판단과 책임은 전적으로 사용자 본인에게 있습니다.
/ENG Version.
This script is designed to use historical drawdown data and automatically enter positions when a predefined percentage drop from the all-time high occurs, using a predefined percentage of your account equity.
You can use leverage, and default parameter values are provided out of the box (you can freely change them to suit your style).
In addition to the two main entry levels, you can add more entry conditions and custom entry percentages – just ask ChatGPT to modify the script.
For actual/live usage, please turn OFF the KillSwitch function and turn ON the Bar Magnifier feature.
ATH Drawdown Re-Buy Long Only Strategy
1. Strategy Overview
The ATH Drawdown Re-Buy Long Only strategy is an automatic re-buy (Long Only) system that builds long positions step-by-step at specific drawdown levels, based on the asset’s all-time high (ATH) and its subsequent drawdown.
This strategy is designed with the following goals:
Systematic scaled buying and leverage usage during sharp correction periods
Clear, rule-based entry logic using drawdowns from ATH
Real-time visualization of:
Average entry price
Leverage
Estimated liquidation price
Account MDD (Max Drawdown)
Return / performance
This allows traders to intuitively monitor both risk and position status.
※ This strategy is provided for educational, research, and backtesting purposes only.
It does not constitute investment advice and does not guarantee any profits.
2. Core Concepts
2-1. Drawdown from ATH (All-Time High)
On the chart, the strategy always tracks the highest high as the ATH.
Whenever a new high is made, ATH is updated, and based on that ATH the following are calculated:
How many percent the current bar’s Low is below the ATH
How many percent the current bar’s Close is below the ATH
Using these, the strategy executes buys at two predefined drawdown zones:
1st entry zone: When price drops X% from ATH
2nd entry zone: When price drops Y% from ATH
Each zone is allowed to trigger only once per ATH cycle.
When a new ATH is created, the “1st / 2nd entry possible” flags are reset, and new opportunities open up for that ATH leg.
2-2. Special Rule for the First Position (100% / 300%)
A key feature of this strategy is the special rule for the very first position.
When the strategy currently holds no position and is about to open the first long position:
Under normal conditions, it builds the position using 100% of account equity.
However, if at that moment the price has dropped by at least a predefined threshold from ATH (e.g. around –72.5% or more),
→ the strategy will open the first position using 300% of account equity.
This rule works as follows:
Whether the first entry happens at the 1st drawdown zone or at the 2nd drawdown zone,
If the current drawdown from ATH is at or below the threshold (e.g. –72.5% or worse),
→ the strategy interprets this as “a sufficiently deep crash” and opens the initial position with 300% of equity.
If the drawdown is less severe than the threshold,
→ the first entry is capped at 100% of equity.
So the strategy has two modes for the first entry:
Normal market conditions: 100% of equity
Deep drawdown conditions: 300% of equity
This special rule is intended to be aggressive in extremely deep crashes while staying more conservative in normal corrections.
3. Strategy Logic & Execution
3-1. Entry Conditions
The strategy tracks the ATH using the High price.
For each bar, it calculates the drawdown from ATH.
The user defines two drawdown zones, for example:
1st zone: ATH – 50%
2nd zone: ATH – 72.5%
For each zone, the strategy checks:
If no buy has been executed yet for that zone in the current ATH leg, and
If the current bar’s Low touches or falls below that zone’s price level,
→ That bar is considered to have triggered a buy condition.
Order simulation:
The strategy simulates entering a long position at that zone’s price level
(using a limit/market-like approximation for backtesting).
3-2. ATH Reset & Entry Opportunity Reset
When a new High goes above the previous ATH:
The ATH is updated to this new high.
Internal flags that track whether the 1st and 2nd entries have been used are reset.
This means:
Each time the market makes a new ATH,
The strategy once again has a fresh opportunity to execute 1st and 2nd drawdown entries for that new ATH leg.
4. Position Sizing & Leverage
4-1. Position Size Based on Account Equity
The strategy defines current equity as:
Current Equity = Initial Capital + Realized PnL + Unrealized PnL
For each entry zone, the position value is calculated as follows:
The user inputs:
“What % of equity to use at this zone”
The strategy:
Multiplies current equity by that percentage
Then multiplies by the strategy’s leverage factor
Thus:
Position Value = Current Equity × (Zone % / 100) × Leverage
Finally, this position value is divided by the entry price to determine the actual position size in tokens.
4-2. Exception for the First Position (100% / 300%)
For the very first position (when there is no open position),
the strategy does not use the zone % parameters. Instead, it uses fixed ratios:
Default: Enter the first position with 100% of equity.
If the drawdown from ATH at that moment is greater than or equal to a predefined threshold (e.g. –72.5% or more)
→ Enter the first position with 300% of equity.
The position value is computed as:
Position Value = Current Equity × (100% or 300%) × Leverage
Then it is divided by the entry price to obtain the token quantity.
This rule:
Applies regardless of whether the first entry occurs at the 1st zone or 2nd zone.
Embeds the philosophy:
“In very deep crashes, go much larger on the first entry; otherwise, stay more conservative.”
4-3. Tracking Real Leverage
On each bar, the strategy tracks:
The existing position size at the start of the bar
The newly added size (if any) on that bar
When a new entry occurs, it calculates the real leverage at that moment:
Real Leverage = (Position Value / Current Equity)
This is then displayed on the chart as a label, for example:
Lev 2.53x
This makes it easy to see the actual leverage level at each entry point.
5. Visualization & Monitoring
5-1. On-Chart Visual Elements
The strategy plots the following directly on the chart:
ATH Line
The all-time high (based on High) is plotted as an orange line.
Average Entry Price Line
When a position is open, the average entry price of that position is plotted as a yellow line.
Estimated Liquidation Price (Fixed) Line
The strategy detects when the position size changes.
At each size change, it uses the current average entry price and real leverage to compute an approximate liquidation price.
This “fixed liquidation price” is then plotted as a red line on the chart.
If there is no position, or if leverage is 1x or lower, the liquidation line is removed.
Entry Markers & Labels
When 1st/2nd entry conditions are met, the strategy:
Marks the entry point on the chart.
Displays labels such as "Buy XX% @ Price" and "Lev XXx",
showing both entry percentage and real leverage at that time.
The label placement is configurable:
Below Bar
Above Bar
At Price
5-2. Information Table (Top-Right Panel)
In the top-right corner of the chart, the strategy displays a summary table of the current account and position status. It typically includes:
Pos Qty (Token)
Absolute size of the current position (in tokens)
Pos Value (USDT)
Market value of the current position (qty × current price)
Leverage (Now)
Current real leverage (position value / current equity)
DD from ATH (%)
Current drawdown (%) from the latest ATH, based on current price
Avg Entry
Average entry price of the current position
PnL (%)
Unrealized profit/loss (%) of the current position
Max DD (Equity %)
The maximum equity drawdown (MDD) recorded over the entire backtest period
Last Entry Price
Average entry price immediately after the most recent add-on entry
Last Entry Lev
Real leverage at the time of the most recent entry
Liq Price (Fixed)
The fixed estimated liquidation price described above
Return from Start (%)
Total return (%) of equity compared to the initial capital
Through this table, users can quickly grasp:
Current account and position status
Current risk level
Cumulative performance
6. Time Filters & Label Options
6-1. Strategy Date Range Filter
The strategy provides an option to restrict trading to a specific time range.
When “Use Date Range” is enabled:
You can specify start and end timestamps.
The strategy will only execute trades within that range.
When this option is disabled:
The strategy operates over the entire chart history.
6-2. Entry Label Placement
Users can customize where entry/leverage labels are drawn:
Below Bar (Below Bar)
Above Bar (Above Bar)
At the actual price level (At Price)
This allows you to adjust visualization according to personal preference and chart readability.
7. Use Cases & Applications
This strategy is suitable for the following purposes:
Long-term / swing-style re-buy strategies for spot or futures long positions
Testing rule-based strategies that rely on “drawdown from ATH” as a main signal
Monitoring account leverage, liquidation price, and MDD when using leverage
Handling situations where, for a given asset:
“Every time a new ATH is formed,
you want to wait for deep corrections and enter only at specific drawdown zones”
It is generally recommended to use this strategy not as a direct plug-and-play live system, but as a tool for:
Strategy idea validation
Risk profile analysis
Parameter exploration to match your personal risk tolerance and style
8. Limitations & Warnings
Backtest results do not guarantee future performance.
They are based on historical data only.
In live markets, additional factors exist:
Liquidity
Slippage
Fee structures
Exchange-specific liquidation rules
Funding fees, etc.
The liquidation price is only an approximate estimate, derived from a simplified formula.
Actual liquidation rules, maintenance margin requirements, fees, and other details differ by exchange.
The liquidation line should be treated as a reference indicator, not an exact guarantee.
Depending on the configured leverage and entry percentages, losses can be very large.
In particular, extremely aggressive settings such as “first position 300% of equity” can greatly increase the risk of large account drawdowns and liquidation during sharp market crashes.
Use such settings with extreme caution.
For live trading, additional risk management is essential:
Your own stop-loss rules
Maximum position size limits
Portfolio-level exposure controls
And other external safety mechanisms beyond this strategy
9. Conclusion
The ATH Drawdown Re-Buy Long Only strategy goes beyond simple “buy the dip” logic. It:
Systematically utilizes drawdowns from ATH as a structural signal
Applies a special first-position rule (100% / 300%)
Integrates visualization of leverage, liquidation price, MDD, and returns
All of this supports rule-based long position building in drawdown phases and comprehensive risk monitoring.
With this strategy, users can:
Explore different:
Drawdown zones
Entry percentages
Leverage levels
Run various backtests and scenario analyses
Better understand the risk/return profile that fits their own market view and risk tolerance
Once again, this strategy is intended for research, learning, and backtesting only.
All real trading decisions and their consequences are solely the responsibility of the user.
LiquidityPulse — RSI + Candle Strength Momentum Reversal SuiteLiquidityPulse — RSI + Candle Strength Momentum Reversal Suite description:
Non-repainting indicator.
⚙️ First-time Setup – Make the Candles Visible
To see the custom candle colours correctly you must disable the chart’s own candle borders and wicks:
Right-click anywhere on your chart (or click the ⚙ gear icon) and choose Settings.
Open the Appearance tab → Candles section.
Untick both Body Borders and Wicks (or set their colours to 100 % transparent).
Click OK.
Without this step the platform’s default candle styling can hide the indicator’s dynamic candle fills.
Overview
This script merges price-action strength with momentum extremes to highlight potentially significant market turning points:
Candle Strength 1–10 – Every candle is graded on a ten-point scale based on body size and volume relative to recent averages. Strong bullish or bearish candles are colour-coded with one of five optional themes (Classic, Cool, Neon, Pastel or Abyss).
RSI Extremes Filter – A standard 14-period RSI monitors overbought and oversold levels.
Only when both a high-grade candle and an RSI extreme occur together does the script optionally plot an arrow to mark a potential reversal area.
How It Works
Each candle receives a bull or bear strength score (1–10) using an internal candle-strength scoring formula.
RSI is checked across a user-defined look-back window (default 2 bars).
Bull Arrow Marker – printed below the bar only when
Bull strength ≥ Min candle strength (default 8), and
RSI dips below the oversold level (default 30) within the look-back window.
Bear Arrow Marker – printed above the bar only when
Bear strength ≥ Min candle strength (default 8), and
RSI rises above the overbought level (default 70) within the look-back window.
These dual conditions make the arrows intentionally rare depending on the settings used, and are designed to highlight momentum conditions associated with potential turning points
How to Use It in Your Own Trading
Market Context First – Apply the indicator only after you have identified the broader trend or key support/resistance areas on higher time-frames.
Confirmation, Not Prediction – Use the arrows as a confirmation of potential exhaustion or reversal; they are not intended as stand-alone entry triggers.
Adjust to Your Style –
Short-term traders might reduce the “RSI look-back bars” to 1 for quicker but more frequent alerts.
Swing traders may raise the “Min candle strength” to 9 or 10 to focus only on the strongest setups.
Combine with Risk Management – Always confirm with your own stop-loss and position-sizing rules.
Why this indicator is useful:
Confluence – It joins price-action strength (candle/volume) with a classic momentum oscillator (RSI), reducing noise from using either method alone.
Visual Clarity – Dynamic candle colouring makes market strength visible at a glance; depending on the settings used, rare arrows can highlight potential reversal areas based on momentum conditions.
Flexibility – All parameters adapt to any market or timeframe.
Educational Value – It helps traders learn how momentum extremes and candle strength interact—valuable for both beginners and experienced traders.
Inputs – Default Values
Min candle strength: 8
RSI look-back bars: 2
Overbought level: 70
Oversold level: 30
Candle-Strength engine: look-back 50 bars, ATR length 14, Body ≥ 0.5×ATR, Volume floor 10 000, Sensitivity 2
Optional features: five colour themes, strength number labels, label background at 42 % opacity.
All settings can be modified to suit different markets and trading styles.
Alerts
Two built-in alert conditions:
Bull Candle-RSI Condition
Bear Candle-RSI Condition
These can trigger alerts when the conditions are met.
If you have any questions about the indicator just pop me a message, happy trading!
Disclaimer
This script is 100 % my own original work.
Trading and investing involve substantial risk and are not suitable for every investor.
This indicator is provided for educational and informational purposes only to assist individuals with their own market analysis.
It is not a buy or sell signal and should not be considered financial advice.
Use it only in conjunction with your own analysis and trade at your own risk.
ProfitView Strategy TemplateHello traders,
This script took me a full week of coding/testing, sweat, and tears - and I’m too nice as I’m giving it for free to the community.
If you're tired of manual trading and looking for a solid strategy template to pair with your indicators, look no further.
This Pine Script v5 strategy template is engineered for maximum customization and risk management.
Best part?
This Pine Script v5 template facilitates the dynamic construction of ProfitView alerts, sparing users the time and effort of mastering the ProfitView syntax and manually creating alert commands.
This powerful tool gives much power to those who don't know how to code in Pinescript and want to automate their indicators' signals via the ProfitView Chrome extension.
IMPORTANT NOTES
ProfitView is a trading bot software that forwards TradingView alerts to your brokers (examples: Binance, Oanda, Coinbase, Bybit, etc.) for automating trading.
Many traders don't know how to dynamically create ProfitView-compatible alerts using the data from their TradingView scripts.
Traders using trading bots want their alerts to reflect the stop-loss/take-profit/trailing-stop/stop-loss to break options from your script and then create the orders accordingly.
This script showcases how to create ProfitView alerts dynamically.
TRADINGVIEW ALERTS
1) You'll have to create one alert per asset X timeframe = 1 chart.
Example: 1 alert for EUR/USD on the 5 minutes chart, 1 alert for EUR/USD on the 15-minute chart (assuming you want your bot to trade the EUR/USD on the 5 and 15-minute timeframes)
2) Select the Order fills and alert() function calls condition
3) For each alert, the alert message is pre-configured with the text below
{{strategy.order.alert_message}}
Please leave it as it is.
It's a TradingView native variable that will fetch the alert text messages built by the script.
4) ProfitView doesn't use webhook technology, so setting a webhook URL from the alerts notifications tab is unnecessary.
KEY FEATURES
I) Modular Indicator Connection
* plug your existing indicator into the template.
* Only two lines of code are needed for full compatibility.
Step 1: Create your connector
Adapt your indicator with only 2 lines of code and then connect it to this strategy template.
To do so:
1) Find in your indicator where the conditions print the long/buy and short/sell signals.
2) Create an additional plot as below
I'm giving an example with a Two moving averages cross.
Please replicate the same methodology for your indicator, whether a MACD , ZigZag, Pivots , higher-highs, lower-lows or whatever indicator with clear buy and sell conditions.
//@version=5
indicator("Supertrend", overlay = true, timeframe = "", timeframe_gaps = true)
atrPeriod = input.int(10, "ATR Length", minval = 1)
factor = input.float(3.0, "Factor", minval = 0.01, step = 0.01)
= ta.supertrend(factor, atrPeriod)
supertrend := barstate.isfirst ? na : supertrend
bodyMiddle = plot(barstate.isfirst ? na : (open + close) / 2, display = display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style = plot.style_linebr)
downTrend = plot(direction < 0 ? na : supertrend, "Down Trend", color = color.red, style = plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps = false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps = false)
buy = ta.crossunder(direction, 0)
sell = ta.crossunder(direction, 0)
//////// CONNECTOR SECTION ////////
Signal = buy ? 1 : sell ? -1 : 0
plot(Signal, title = "Signal", display = display.data_window)
//////// CONNECTOR SECTION ////////
Important Notes
🔥 The Strategy Template expects the value to be exactly 1 for the bullish signal and -1 for the bearish signal
Now, you can connect your indicator to the Strategy Template using the method below or that one.
Step 2: Connect the connector
1) Add your updated indicator to a TradingView chart
2) Add the Strategy Template as well to the SAME chart
3) Open the Strategy Template settings, and in the Data Source field, select your 🔌Connector🔌 (which comes from your indicator)
Note it doesn’t have to be named 🔌Connector🔌 - you can name it as you want - however, I recommend an explicit name you can easily remember.
From then, you should start seeing the signals and plenty of other stuff on your chart.
🔥 Note that whenever you update your indicator values, the strategy statistics and visuals on your chart will update in real-time
II) BOT Risk Management:
- Max Drawdown:
Mode: Select whether the max drawdown is calculated in percentage (%) or USD.
Value: If the max drawdown reaches this specified value, set a value to halt the bot.
- Max Consecutive Days:
Use Max Consecutive Days BOT Halt: Enable/Disable halting the bot if the max consecutive losing days value is reached.
- Max Consecutive Days: Set the maximum number of consecutive losing days allowed before halting the bot.
- Max Losing Streak:
Use Max Losing Streak: Enable/Disable a feature to prevent the bot from taking too many losses in a row.
- Max Losing Streak Length: Set the maximum length of a losing streak allowed.
Margin Call:
- Use Margin Call: Enable/Disable a feature to exit when a specified percentage away from a margin call to prevent it.
Margin Call (%): Set the percentage value to trigger this feature.
- Close BOT Total Loss:
Use Close BOT Total Loss: Enable/Disable a feature to close all trades and halt the bot if the total loss is reached.
- Total Loss ($): Set the total loss value in USD to trigger this feature.
Intraday BOT Risk Management:
- Intraday Losses:
Use Intraday Losses BOT Halt: Enable/Disable halting the bot on reaching specified intraday losses.
Mode: Select whether the intraday loss is calculated in percentage (%) or USD.
- Max Intraday Losses (%): Set the value for maximum intraday losses.
Limit Intraday Trades:
- Use Limit Intraday Trades: Enable/Disable a feature to limit the number of intraday trades.
- Max Intraday Trades: Set the maximum number of intraday trades allowed.
Restart Intraday EA:
- Use Restart Intraday EA: Enable/Disable a feature to restart the bot at the first bar of the next day if it has been stopped with an intraday risk management safeguard.
III) Order Types and Position Sizing
- Choose between market, limit, or stop orders.
- Set your position size directly in the template.
Please use the position size from the “Inputs” and not the “Properties” tab.
I know it's redundant. - the template needs this value from the "Inputs" tab to build the alerts, and the Backtester needs it from the "Properties" tab.
IV) Advanced Take-Profit and Stop-Loss Options
- Choose to set your SL/TP in either pips or percentages.
- Option for multiple take-profit levels and trailing stop losses.
- Move your stop loss to break even +/- offset in pips for “risk-free” trades.
V) Miscellaneous
Retry order openings if they fail.
Order Types:
Select and specify order type and price settings.
Position Size:
Define the type and size of positions.
Leverage:
Leverage settings, including margin type and hedge mode.
Session:
Limit trades to specific sessions.
Dates:
Limit trades to a specific date range.
Trades Direction:
Direction: Specify the market direction for opening positions.
VI) Notifications (Telegram/Discord/Email/IFTTT/Twilio/SMS)
Customize notifications sent to Telegram, Discord, Email, IFTTT, Twilio, and ProfitView Logger.
VII) Logger
The ProfitView commands are logged in the TradingView logger.
You'll find more information about it in this TradingView blog post .
WHY YOU MIGHT NEED THIS TEMPLATE
1) Transform your indicator into a ProfitView trading bot more easily than before
Connect your indicator to the template
Create your alerts
Set your EA settings
2) Save Time
Auto-generated alert messages for ProfitView.
I tested them all and checked with the support team what could/couldn’t be done.
3) Be in Control
Manage your trading risks with advanced features.
4) Customizable
Fits various trading styles and asset classes.
REQUIREMENTS
* Make sure you have your ProfitView account and do the settings correctly in your Chrome extension. If you don't know how to do it, read the documentation + ask for help in the ProfitView Discord support channel.
* If there is any issue with the template, ask me in the comments section - I’ll answer quickly.
BACKTEST RESULTS FROM THIS POST
1) I connected this strategy template to a dummy Supertrend script.
I could have selected any other indicator or concept for this script post.
I wanted to share an example of how you can quickly upgrade your strategy, making it compatible with ProfitView.
2) The backtest results aren't relevant for this educational script publication.
I used realistic backtesting data but didn't look too much into optimizing the results, as this isn't the point of why I'm publishing this script.
This strategy is a template to be connected to any indicator - the sky is the limit. :)
3) This template is made to take 1 trade per direction at any given time.
Pyramiding is set to 1 on TradingView.
The strategy default settings are:
* Initial Capital: 100000 USD
* Position Size: 1%
* Commission Percent: 0.075%
* Slippage: 1 tick
* No margin/leverage used
Best regards,
Dave
TradingView.To Strategy Template (with Dyanmic Alerts)Hello traders,
If you're tired of manual trading and looking for a solid strategy template to pair with your indicators, look no further.
This Pine Script v5 strategy template is engineered for maximum customization and risk management.
Best part?
This Pine Script v5 template facilitates the dynamic construction of TradingView.TO alerts, sparing users the time and effort of mastering the TradingView.TO syntax and manually create alert commands.
This powerful tool gives much power to those who don't know how to code in Pinescript and want to automate their indicators' signals via TradingView.TO bot.
IMPORTANT NOTES
TradingView.TO is a trading bot software that forwards TradingView alerts to your brokers (examples: Binance, Oanda, Coinbase, Bybit, Metatrader 4/5, ...) for automating trading.
Many traders don't know how to create TradingView.TO dynamically-compatible alerts using the data from their TradingView scripts.
Traders using trading bots want their alerts to reflect the stop-loss/take-profit/trailing-stop/stop-loss to break options from your script and then create the orders accordingly.
This script showcases how to create TradingView.TO alerts dynamically.
TRADINGVIEW ALERTS
1) You'll have to create one alert per asset X timeframe = 1 chart.
Example: 1 alert for BTC/USDT on the 5 minutes chart, 1 alert for BTC/USDT on the 15-minute chart (assuming you want your bot to trade the BTC/USDT on the 5 and 15-minute timeframes)
2) Select the Order fills and alert() function calls condition
3) For each alert, the alert message is pre-configured with the text below
{{strategy.order.alert_message}}
Please leave it as it is.
It's a TradingView native variable that will fetch the alert text messages built by the script.
4) TradingView.TO uses webhook technology - setting a webhook URL from the alerts notifications tab is required.
KEY FEATURES
I) Modular Indicator Connection
* plug your existing indicator into the template.
* Only two lines of code are needed for full compatibility.
Step 1: Create your connector
Adapt your indicator with only 2 lines of code and then connect it to this strategy template.
To do so:
1) Find in your indicator where the conditions print the long/buy and short/sell signals.
2) Create an additional plot as below
I'm giving an example with a Two moving averages cross.
Please replicate the same methodology for your indicator, whether a MACD , ZigZag, Pivots , higher-highs, lower-lows or whatever indicator with clear buy and sell conditions.
//@version=5
indicator("Supertrend", overlay = true, timeframe = "", timeframe_gaps = true)
atrPeriod = input.int(10, "ATR Length", minval = 1)
factor = input.float(3.0, "Factor", minval = 0.01, step = 0.01)
= ta.supertrend(factor, atrPeriod)
supertrend := barstate.isfirst ? na : supertrend
bodyMiddle = plot(barstate.isfirst ? na : (open + close) / 2, display = display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style = plot.style_linebr)
downTrend = plot(direction < 0 ? na : supertrend, "Down Trend", color = color.red, style = plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps = false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps = false)
buy = ta.crossunder(direction, 0)
sell = ta.crossunder(direction, 0)
//////// CONNECTOR SECTION ////////
Signal = buy ? 1 : sell ? -1 : 0
plot(Signal, title = "Signal", display = display.data_window)
//////// CONNECTOR SECTION ////////
Important Notes
🔥 The Strategy Template expects the value to be exactly 1 for the bullish signal and -1 for the bearish signal
Now, you can connect your indicator to the Strategy Template using the method below or that one.
Step 2: Connect the connector
1) Add your updated indicator to a TradingView chart
2) Add the Strategy Template as well to the SAME chart
3) Open the Strategy Template settings, and in the Data Source field, select your 🔌Connector🔌 (which comes from your indicator)
Note it doesn’t have to be named 🔌Connector🔌 - you can name it as you want - however, I recommend an explicit name you can easily remember.
From then, you should start seeing the signals and plenty of other stuff on your chart.
🔥 Note that whenever you update your indicator values, the strategy statistics and visuals on your chart will update in real-time
II) BOT Risk Management:
- Max Drawdown:
Mode: Select whether the max drawdown is calculated in percentage (%) or USD.
Value: If the max drawdown reaches this specified value, set a value to halt the bot.
- Max Consecutive Days:
Use Max Consecutive Days BOT Halt: Enable/Disable halting the bot if the max consecutive losing days value is reached.
- Max Consecutive Days: Set the maximum number of consecutive losing days allowed before halting the bot.
- Max Losing Streak:
Use Max Losing Streak: Enable/Disable a feature to prevent the bot from taking too many losses in a row.
- Max Losing Streak Length: Set the maximum length of a losing streak allowed.
Margin Call:
- Use Margin Call: Enable/Disable a feature to exit when a specified percentage away from a margin call to prevent it.
Margin Call (%): Set the percentage value to trigger this feature.
- Close BOT Total Loss:
Use Close BOT Total Loss: Enable/Disable a feature to close all trades and halt the bot if the total loss is reached.
- Total Loss ($): Set the total loss value in USD to trigger this feature.
Intraday BOT Risk Management:
- Intraday Losses:
Use Intraday Losses BOT Halt: Enable/Disable halting the bot on reaching specified intraday losses.
Mode: Select whether the intraday loss is calculated in percentage (%) or USD.
- Max Intraday Losses (%): Set the value for maximum intraday losses.
Limit Intraday Trades:
- Use Limit Intraday Trades: Enable/Disable a feature to limit the number of intraday trades.
- Max Intraday Trades: Set the maximum number of intraday trades allowed.
Restart Intraday EA:
III) Order Types and Position Sizing
- Choose between market or limit orders.
- Set your position size directly in the template.
Please use the position size from the “Inputs” and not the “Properties” tab.
I know it's redundant. - the template needs this value from the "Inputs" tab to build the alerts, and the Backtester needs it from the "Properties" tab.
IV) Advanced Take-Profit and Stop-Loss Options
- Choose to set your SL/TP in either USD or percentages.
- Option for multiple take-profit levels and trailing stop losses.
- Move your stop loss to break even +/- offset in USD for “risk-free” trades.
V) Miscellaneous:
Retry order openings if they fail.
Order Types:
Select and specify order type and price settings.
Position Size:
Define the type and size of positions.
Leverage:
Leverage settings, including margin type and hedge mode.
Session:
Limit trades to specific sessions.
Dates:
Limit trades to a specific date range.
Trades Direction:
Direction: Specify the market direction for opening positions.
VI) Logger
The TradingView.TO commands are logged in the TradingView logger.
You'll find more information about it in this TradingView blog post .
WHY YOU MIGHT NEED THIS TEMPLATE
1) Transform your indicator into a TradingView.TO trading bot more easily than before
Connect your indicator to the template
Create your alerts
Set your EA settings
2) Save Time
Auto-generated alert messages for TradingView.TO.
I tested them all and checked with the support team what could/couldn’t be done.
3) Be in Control
Manage your trading risks with advanced features.
4) Customizable
Fits various trading styles and asset classes.
REQUIREMENTS
* Make sure you have your TradingView.TO account
* If there is any issue with the template, ask me in the comments section - I’ll answer quickly.
BACKTEST RESULTS FROM THIS POST
1) I connected this strategy template to a dummy Supertrend script.
I could have selected any other indicator or concept for this script post.
I wanted to share an example of how you can quickly upgrade your strategy, making it compatible with TradingView.TO.
2) The backtest results aren't relevant for this educational script publication.
I used realistic backtesting data but didn't look too much into optimizing the results, as this isn't the point of why I'm publishing this script.
This strategy is a template to be connected to any indicator - the sky is the limit. :)
3) This template is made to take 1 trade per direction at any given time.
Pyramiding is set to 1 on TradingView.
The strategy default settings are:
* Initial Capital: 100000 USD
* Position Size: 1%
* Commission Percent: 0.075%
* Slippage: 1 tick
* No margin/leverage used






















